package com.crm.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.fastdfs.FastDFSClient;
import com.crm.model.entity.sys.FileUpload;
import com.crm.system.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author luojie
 * @date 2020/12/21 16:25
 */
@RestController
@Slf4j
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    private FastDFSClient fastDFSClient = new FastDFSClient();
    /**
     * 上传附件(多文件上传)
     * @param request
     * @param files
     * @return
     */
    @PostMapping("/file/upload")
    public DataResponse fileUpload(HttpServletRequest request,
                                   @RequestParam MultipartFile[] files
                                   ){
        //UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        List<FileUpload> fileUploads = new ArrayList<>();
        // 多文件上传
        for (MultipartFile multipartFile : files){
            // 文件名
            String fileName  = multipartFile.getOriginalFilename();
            // 文件类型
            String contentType = FilenameUtils.getExtension(fileName).toLowerCase();

/*            long time = System.currentTimeMillis();
            // 存储路径String
            String userAccountIdStr = userAccount.getAccountId().replace("-","")+ "."+ contentType;

            //定义文件路径
            String filePath = FileUtil.generateFilePath(time,userAccountIdStr, "");
            File file = new File(filePath);*/

            try {
/*                String accessUrl = "";
                // 保存文件
                multipartFile.transferTo(file);
                String crmIp = PathUtil.getCrmIp();//IP
                String port = PathUtil.getPort();//端口
                String accessPath = PathUtil.getAccessPath();
                if("www.dcrm.cn".equals(crmIp)){
                    accessUrl="https://" + crmIp + accessPath + time + userAccountIdStr;//服务器运行项目
                }else {
                    accessUrl="http://" + crmIp + ":" + port + accessPath + time + userAccountIdStr;//本地运行项目
                }
                String fileId = fileUploadService.insertFileUpload(fileName,filePath,accessUrl,contentType);

                //如果文件为word则另存word文件为pdf格式（前端返回pdf文件的绝对路径，下载时使用word文件的绝对路径）
                if(fileName.endsWith("docx")||fileName.endsWith("doc")){
                    String filePdfPath = filePath.substring(0,filePath.lastIndexOf("."))+".pdf";
                    FileUtil.doc2pdf(filePath,filePdfPath);
                }*/
                String fileSaveUrl = fastDFSClient.uploadFileWithMultipart(multipartFile);
                String accessUrl = "https://fastdfs.dcrm.cn/"+fileSaveUrl;
                String fileId = fileUploadService.insertFileUpload(fileName,fileSaveUrl,accessUrl,contentType);

                //拼凑返回值
                if(!StringUtils.isBlank(fileId)){
                    FileUpload fileUpload = new FileUpload();
                    fileUpload.setUploadId(fileId);
                    fileUpload.setAccessUrl(accessUrl);
                    fileUpload.setFileName(fileName);
                    fileUpload.setFilePath(fileSaveUrl);
                    fileUpload.setFileType(contentType);
                    fileUploads.add(fileUpload);
                }
            } catch (Exception e) {
                log.error("file upload error:", e);
            }
        }
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),fileUploads);
    }

    /**
     * 单文件上传
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/file/uploadByOneFile")
    public DataResponse uploadByOneFile(HttpServletRequest request,
                                   @RequestParam MultipartFile file){
        JSONObject result = new JSONObject();
        //UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        // 单文件上传
        // 文件名
        String fileName  = file.getOriginalFilename();
        // 文件类型
        String contentType = FilenameUtils.getExtension(fileName).toLowerCase();
        /*String userAccountIdStr = userAccount.getAccountId().replace("-","")+ "."+ contentType;
        long time = System.currentTimeMillis();
        // 存储路径String

        //定义文件路径
        String filePath = FileUtil.generateFilePath(time,userAccountIdStr, "");
        File fileUpload = new File(filePath);*/

        try {
            // 保存文件
            //file.transferTo(fileUpload);
            String fileSaveUrl = fastDFSClient.uploadFileWithMultipart(file);
            String accessUrl = "https://fastdfs.dcrm.cn/"+fileSaveUrl;
/*            String crmIp = PathUtil.getCrmIp();//IP
            String port = PathUtil.getPort();//端口
            String accessPath = PathUtil.getAccessPath();
            if("www.dcrm.cn".equals(crmIp)){
                accessUrl="https://" + crmIp + accessPath + time + userAccountIdStr;//服务器运行项目
            }else {
                accessUrl="http://" + crmIp + ":" + port + accessPath + time + userAccountIdStr;//本地运行项目
            }*/
            String fileId = fileUploadService.insertFileUpload(fileName,fileSaveUrl,accessUrl,contentType);
            if(!StringUtils.isBlank(fileId)){
                result.put("fileId",fileId);
            }
            result.put("accessUrl",accessUrl);
            result.put("fileType",contentType);

            //如果文件为word则另存word文件为pdf格式（前端返回pdf文件的绝对路径，下载时使用word文件的绝对路径）
/*            if(fileName.endsWith("docx")||fileName.endsWith("doc")){
                String filePdfPath = filePath.substring(0,filePath.lastIndexOf("."))+".pdf";
                FileUtil.doc2pdf(filePath,filePdfPath);
            }*/
        } catch (Exception e) {
            log.error("file upload error:", e);
        }
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),result);
    }


    /**
     * 单文件上传
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/file/uploadByOneFileEdit")
    public JSONObject uploadByOneFileEdit(HttpServletRequest request,
                                   @RequestParam MultipartFile file){
        JSONObject result = new JSONObject();
        //UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        // 单文件上传
        // 文件名
        String fileName  = file.getOriginalFilename();
        // 文件类型
        String contentType = FilenameUtils.getExtension(fileName).toLowerCase();

        /*String userAccountIdStr = userAccount.getAccountId().replace("-","")+ "."+ contentType;

        long time = System.currentTimeMillis();
        // 存储路径String

        //定义文件路径
        String filePath = FileUtil.generateFilePath(time,userAccountIdStr, "");
        File fileUpload = new File(filePath);*/

        try {
            /*
            String accessUrl = "";
            // 保存文件
            file.transferTo(fileUpload);
            String crmIp = PathUtil.getCrmIp();//IP
            String port = PathUtil.getPort();//端口
            String accessPath = PathUtil.getAccessPath();
            if("dcrm.cn".equals(crmIp)){
                accessUrl="https://" + crmIp + accessPath + time + userAccountIdStr;//服务器运行项目
            }else {
                accessUrl="http://" + crmIp + ":" + port + accessPath + time + userAccountIdStr;//本地运行项目
            }*/
            String fileSaveUrl = fastDFSClient.uploadFileWithMultipart(file);
            String accessUrl = "https://fastdfs.dcrm.cn/"+fileSaveUrl;
            String fileId = fileUploadService.insertFileUpload(fileName,fileSaveUrl,accessUrl,contentType);
            result.put("link",accessUrl);

        } catch (Exception e) {
            log.error("file upload error:", e);
        }
        return result;
    }

    /**
     * 文件删除
     * @param request
     * @param filePaths
     * @return
     */
    @PostMapping("/file/deleteFile")
    public DataResponse deleteFile(HttpServletRequest request,
                                   //@RequestParam MultipartFile[] files){
                                   @RequestParam String filePaths){
        String result = "";
        List<String> fileIdList = Arrays.asList(filePaths);
        // 多文件删除
        for (String id : fileIdList) {
            FileUpload fileUpload = fileUploadService.selectFileUploadById(id);
            //定义文件路径
            File filePath = new File(fileUpload.getFilePath());
            if (filePath.exists()) {//文件是否存在
                if (filePath.delete()) {//存在就删了，返回1
                    result =  ResponseCodeEnum.OK.getResponseCode();
                    //删除文件数据库记录
                    Boolean delResult = fileUploadService.deleteFileUploadById(id);
                } else {
                    result =  ResponseCodeEnum.ERROR.getResponseCode();
                }
            } else {
                result = ResponseCodeEnum.FILE_NOT_EXIST.getResponseCode();
            }
        }

       return new DhResponse(result);
    }



}

